package org.wzg.aityweb.Repostry;

import dev.langchain4j.data.message.ChatMessage;
import dev.langchain4j.data.message.ChatMessageDeserializer;
import dev.langchain4j.data.message.ChatMessageSerializer;
import dev.langchain4j.store.memory.chat.ChatMemoryStore;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Repository;

import java.time.Duration;
import java.util.List;
//TODO：注意，redis已经更换为docker-vector向量容器版本，目前为无密码登录，后期若复用该项目，需要修改密码和redis认证模式

@Repository
public class RedisMemory implements ChatMemoryStore {

    @Autowired
    private StringRedisTemplate redisTemplate;
    @Override
    public List<ChatMessage> getMessages(Object memoryId) {
        String string = redisTemplate.opsForValue().get(memoryId);
        //包装返回的结果为List列表
        List<ChatMessage> chatMessages = ChatMessageDeserializer.messagesFromJson(string);
        return chatMessages;
    }

    @Override
    public void updateMessages(Object memoryId, List<ChatMessage> list) {
        String messages = ChatMessageSerializer.messagesToJson(list);
        redisTemplate.opsForValue().set(memoryId.toString(),messages, Duration.ofDays(1));
        System.out.println("更新消息缓存"+memoryId.toString());
    }

    @Override
    public void deleteMessages(Object o) {
         redisTemplate.delete(o.toString());
        System.out.println("删除消息缓存"+o.toString());
    }
}
